"""Auto-Connect Example using .env file settings"""

import asyncio
from fastmcp import Client
import sys
import os

# Add the src directory to the path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from server import mcp, initialize_managers


async def example_auto_connect_workflow():
    """Example: Using auto-connect with .env file settings"""
    print("=== Auto-Connect Workflow Example ===")
    print("This example uses SSH settings from .env file automatically!\n")
    
    async with Client(mcp) as client:
        # Method 1: Auto-connect using .env settings (NEW!)
        print("🚀 Method 1: Auto-connect using .env settings")
        auto_connect_result = await client.call_tool("auto_connect_ssh", {})
        print(f"Auto-connect result:\n{auto_connect_result.text}\n")
        
        # Method 2: Manual connect with .env defaults (all parameters optional)
        print("🔧 Method 2: Manual connect (all parameters optional - uses .env defaults)")
        manual_connect_result = await client.call_tool("connect_ssh", {})
        print(f"Manual connect result:\n{manual_connect_result.text}\n")
        
        # Method 3: Override specific parameters while using .env defaults for others
        print("🔧 Method 3: Override specific parameters (e.g., different port)")
        override_connect_result = await client.call_tool("connect_ssh", {
            "port": 2222  # Override port, use .env for host, username, key_path
        })
        print(f"Override connect result:\n{override_connect_result.text}\n")
        
        # Get connection list to see active connections
        print("📋 Active connections:")
        connections_result = await client.call_tool("list_connections", {})
        print(f"Connections:\n{connections_result.text}\n")


async def example_immediate_workflow():
    """Example: Immediate workflow after auto-connect"""
    print("=== Immediate Workflow Example ===")
    print("Auto-connect and immediately start working!\n")
    
    async with Client(mcp) as client:
        # Auto-connect
        print("🔌 Auto-connecting...")
        connect_result = await client.call_tool("auto_connect_ssh", {})
        print(f"Connection: {connect_result.text[:100]}...\n")
        
        # Extract connection ID (in real implementation, this would be parsed)
        # For demo purposes, we'll use the expected format
        connection_id = "suyuexinghen@cancon.hpccube.com:65023"
        
        # Immediate workflow: List files, check compilers, run commands
        print("📁 Listing remote home directory...")
        files_result = await client.call_tool("list_remote_files", {
            "connection_id": connection_id,
            "directory": "~",
            "pattern": "*"
        })
        print(f"Home directory:\n{files_result.text[:300]}...\n")
        
        print("🔧 Checking available compilers...")
        compiler_result = await client.call_tool("get_compiler_info", {
            "connection_id": connection_id,
            "compiler": ""  # Check all compilers
        })
        print(f"Compilers:\n{compiler_result.text[:200]}...\n")
        
        print("💻 Running your typical workflow...")
        workflow_commands = """
        # Navigate to workspace
        cd ~/workspace
        
        # Check current directory and environment
        pwd
        module list
        
        # Quick system info
        hostname
        date
        """
        
        workflow_result = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": workflow_commands,
            "working_dir": "~",
            "stop_on_error": False
        })
        print(f"Workflow result:\n{workflow_result.text[:400]}...\n")


async def example_project_workflow():
    """Example: Complete project workflow with auto-connect"""
    print("=== Complete Project Workflow ===")
    print("Auto-connect -> Build -> Submit Job\n")
    
    async with Client(mcp) as client:
        # Auto-connect
        print("🔌 Auto-connecting...")
        await client.call_tool("auto_connect_ssh", {})
        connection_id = "suyuexinghen@cancon.hpccube.com:65023"
        
        # Complete project workflow
        print("🏗️ Complete project workflow...")
        project_workflow = """
        # Setup project directory
        mkdir -p ~/projects/simulation_$(date +%Y%m%d)
        cd ~/projects/simulation_$(date +%Y%m%d)
        
        # Create a simple C program
        echo '#include <stdio.h>
        #include <omp.h>
        int main() {
            printf("Starting simulation...\\n");
            #pragma omp parallel for
            for(int i = 0; i < 10; i++) {
                printf("Thread %d processing item %d\\n", omp_get_thread_num(), i);
            }
            printf("Simulation completed!\\n");
            return 0;
        }' > simulation.c
        
        # Compile the program
        gcc -fopenmp simulation.c -o simulation
        
        # Test run
        ./simulation
        
        # Create Slurm job script
        echo '#!/bin/bash
        #SBATCH --job-name=auto_simulation
        #SBATCH --partition=cpu
        #SBATCH --nodes=1
        #SBATCH --cpus-per-task=4
        #SBATCH --time=00:05:00
        #SBATCH --output=simulation_%j.out
        #SBATCH --error=simulation_%j.err
        
        cd $PWD
        export OMP_NUM_THREADS=4
        echo "Job started at: $(date)"
        ./simulation
        echo "Job completed at: $(date)"' > job.slurm
        
        # Submit the job
        sbatch job.slurm
        """
        
        result = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": project_workflow,
            "working_dir": "~",
            "stop_on_error": True
        })
        print(f"Project workflow result:\n{result.text}")


async def main():
    """Run all auto-connect examples"""
    print("SSH Slurm MCP Server - Auto-Connect Examples")
    print("Uses SSH settings from .env file automatically!\n")
    print(f"Current .env settings:")
    print(f"• SSH_HOST: {os.getenv('SSH_HOST', 'Not set')}")
    print(f"• SSH_USERNAME: {os.getenv('SSH_USERNAME', 'Not set')}")
    print(f"• SSH_PORT: {os.getenv('SSH_PORT', 'Not set')}")
    print(f"• SSH_KEY_PATH: {os.getenv('SSH_KEY_PATH', 'Not set')}")
    print("=" * 60 + "\n")
    
    # Initialize managers
    initialize_managers()
    
    await example_auto_connect_workflow()
    await example_immediate_workflow()
    await example_project_workflow()
    
    print("\n🎉 All auto-connect examples completed!")
    print("\n💡 Key Benefits:")
    print("  ✅ No need to enter SSH details every time")
    print("  ✅ Just call auto_connect_ssh() or connect_ssh() with no parameters")
    print("  ✅ Override specific settings when needed")
    print("  ✅ Perfect for regular HPC development workflows")


if __name__ == "__main__":
    asyncio.run(main())
